package com.example.liu_test.service.impl;

import cn.hutool.extra.ssh.JschRuntimeException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.liu_test.mapper.AdminMapper;
import com.example.liu_test.pojo.Admin;
import com.example.liu_test.pojo.RespBean;
import com.example.liu_test.service.IAdminService;
import com.example.liu_test.util.RedisConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 刘旺
 * @since 2021-07-05
 */
@Service
@Transactional
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    protected RedisConfig redisConfigurer;

    @Override
    public RespBean login(String username, String password, HttpServletResponse response) throws Exception {

        Admin userForBase = adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username));
        //验证密码是否正确
        if (!userForBase.getPassword().equals(password)) {
            return RespBean.error("登陆失败");
        } else {
            String token = tokenService.getToken(userForBase);
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            cookie.setHttpOnly(false);
            Cookie ckUsername = new Cookie("nms_username", userForBase.getUsername());
            Cookie ckPassword = new Cookie("nms_password", userForBase.getPassword());
            ckUsername.setPath("/");
            ckPassword.setPath("/");
            ckUsername.setMaxAge(60 * 60 * 24 * 30);
            ckPassword.setMaxAge(60 * 60 * 24 * 30);
            response.addCookie(ckUsername);
            response.addCookie(ckPassword);
            //redisConfigurer.set("test","test");
            System.out.println(redisConfigurer.randomKey());
            response.addCookie(cookie);
            return RespBean.success("登陆成功");
        }

    }

    @Override
    public RespBean logoff(HttpServletResponse response, HttpServletRequest request) throws Exception {
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cookie", request.getCookies());
        return RespBean.success("退出成功", jsonObject);
    }
}